package com.sch.www.oauth.oauth2;

import com.sch.www.sys.feign.AccountApi;
import com.sch.www.sys.orm.entity.manual.Account;
import com.sch.www.sys.orm.entity.manual.Resource;
import com.sch.www.sys.orm.entity.manual.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashSet;

@Component
public class JdbcUserDetailsService implements UserDetailsService {

    @Autowired
    private AccountApi accountApi;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Account account = accountApi.getByUsername(username).getData();
        if (account == null) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        Collection<SimpleGrantedAuthority> simpleGrantedAuthorityCollection = new HashSet<>();
        for (Role role : account.getRoleList()) {
            simpleGrantedAuthorityCollection.add(new SimpleGrantedAuthority(role.getCode()));
        }
        for (Resource resource : account.getResourceList()) {
            simpleGrantedAuthorityCollection.add(new SimpleGrantedAuthority(resource.getPermission()));
        }
        UserDetails userDetails = new org.springframework.security.core.userdetails.User(account.getUsername(), account.getPassword(), simpleGrantedAuthorityCollection);
        return userDetails;
    }
}
